<template>
  <div class="list-common-table">
    <t-dialog :visible="infoVisible" :cancelBtn="null" :onClose="closeInfo" @confirm="closeInfo">
      <t-card title="工单内容" bordered :shadow="true" :style="{ marginBottom: '10px' }">{{ workorderInfo.info }}</t-card>
      <!--      <t-card title="完成情况" bordered :shadow="true" :style="{ marginBottom: '10px' }">
        <t-tag v-if="workorderInfo.status === WORKORDER_STATUS.POSTED" theme="danger" variant="light">未答复</t-tag>
        <t-tag v-if="workorderInfo.status === WORKORDER_STATUS.ANSWERED" theme="success" variant="light">已答复</t-tag>
        <t-tag v-if="workorderInfo.status === WORKORDER_STATUS.CLOSED" variant="light">已关闭</t-tag>
      </t-card> -->
      <t-card title="提交时间" bordered :shadow="true" :style="{ marginBottom: '10px' }">{{ workorderInfo.time }}</t-card>
      <t-card title="工单回复" v-show="workorderInfo.annotation != ''" bordered :shadow="true"
        :style="{ marginBottom: '10px' }">
        <div class="info-block">{{ workorderInfo.annotation }}</div>
      </t-card>
    </t-dialog>

    <t-dialog :visible="modiVisible" :onCancel="closeInfo" :onClose="closeInfo" @confirm="postWorkorder('modi')">
      <t-card title="工单内容" bordered :shadow="true" :style="{ marginBottom: '10px' }">{{ workorderInfo.info }}</t-card>
      <!--      <t-card title="完成情况" bordered :shadow="true" :style="{ marginBottom: '10px' }">
        <t-tag v-if="workorderInfo.status === WORKORDER_STATUS.POSTED" theme="danger" variant="light">未答复</t-tag>
        <t-tag v-if="workorderInfo.status === WORKORDER_STATUS.ANSWERED" theme="success" variant="light">已答复</t-tag>
        <t-tag v-if="workorderInfo.status === WORKORDER_STATUS.CLOSED" variant="light">已关闭</t-tag>
      </t-card> -->
      <t-card title="提交时间" bordered :shadow="true" :style="{ marginBottom: '10px' }">{{ workorderInfo.time }}</t-card>
      <t-card title="工单回复" bordered :shadow="true" :style="{ marginBottom: '10px' }">
        <t-textarea v-model="workorderInfo.annotation" placeholder="请输入回复文案" name="description" />
      </t-card>
      <t-radio-group variant="primary-filled" default-value="1" v-model="workorderInfo.tempstatus"
        v-show="workorderInfo.status == 0">
        <t-radio-button value="1">完结</t-radio-button>
        <t-radio-button value="2">关闭</t-radio-button>
      </t-radio-group>
    </t-dialog>

    <t-dialog :visible="postVisible" :onCancel="closeInfo" :onClose="closeInfo" @confirm="postWorkorder('new')"
      confirmBtn="提交">
      <t-card title="工单内容" bordered :shadow="true" :style="{ marginBottom: '10px' }">
        <t-textarea v-model="postValue" placeholder="请输入描述文案" name="description" />
      </t-card>
    </t-dialog>

    <t-form ref="form" :data="formData" :label-width="80" colon @reset="onReset" @submit="onSubmit">
      <t-row>
        <t-col :span="10">
          <t-row :gutter="[16, 16]">
            <t-col :span="2" v-show="!manager">
              <t-button @click="showPostWorkorder">提交工单</t-button>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="工单状态" name="status">
                <t-select v-model="formData.status" class="form-item-content`" :options="WORKORDER_STATUS_OPTIONS"
                  placeholder="请选择工单状态" />
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="工单编号" name="_id">
                <t-input v-model="formData._id" class="form-item-content" placeholder="请输入工单编号"
                  :style="{ minWidth: '134px' }" />
              </t-form-item>
            </t-col>
            <!-- <t-col :flex="1">
              <t-form-item label="工单内容" name="content">
                <t-input v-model="formData.content" class="form-item-content" placeholder="请输入工单内容"
                  :style="{ minWidth: '134px' }" />
              </t-form-item>
            </t-col> -->
            <!--            <t-col :flex="1">
              <t-form-item label="工单类型" name="type">
                <t-select v-model="formData.type" class="form-item-content`" :options="CONTRACT_TYPE_OPTIONS" placeholder="请选择工单类型" />
              </t-form-item>
            </t-col> -->
          </t-row>
        </t-col>

        <t-col :span="2" class="operation-container">
          <t-button theme="primary" type="submit" :style="{ marginLeft: '8px' }">查询</t-button>
          <t-button type="reset" variant="base" theme="default">重置</t-button>
        </t-col>
      </t-row>
    </t-form>
    <div class="table-container">
      <t-table :data="data" :columns="columns" :rowKey="rowKey" :stripe="defaultTrue" :verticalAlign="verticalAlign"
        :hover="hover" :pagination="pagination" @page-change="rehandlePageChange" @change="rehandleChange"
        :loading="dataLoading">
        <template #status="{ row }">
          <t-tag v-if="row.status === WORKORDER_STATUS.POSTED" theme="danger" variant="light">未答复</t-tag>
          <t-tag v-if="row.status === WORKORDER_STATUS.ANSWERED" theme="success" variant="light">已答复</t-tag>
          <t-tag v-if="row.status === WORKORDER_STATUS.CLOSED" variant="light">已关闭</t-tag>
        </template>

        <!--        <template #contractType="{ row }">
          <p v-if="row.contractType === CONTRACT_TYPES.MAIN">审核失败</p>
          <p v-if="row.contractType === CONTRACT_TYPES.SUB">待审核</p>
          <p v-if="row.contractType === CONTRACT_TYPES.SUPPLEMENT">待履行</p>
        </template> -->
        <!--        <template #paymentType="{ row }">
          <p v-if="row.paymentType === CONTRACT_PAYMENT_TYPES.PAYMENT" class="payment-col">
            付款
            <trend class="dashboard-item-trend" type="up" />
          </p>
          <p v-if="row.paymentType === CONTRACT_PAYMENT_TYPES.RECIPT" class="payment-col">
            收款
            <trend class="dashboard-item-trend" type="down" />
          </p>
        </template> -->
        <template #op="slotProps">
          <t-button @click="rehandleClickOp(slotProps, 'info')" shape="circle">
            <t-icon name="browse"></t-icon>
          </t-button>
          <t-button shape="circle" @click="rehandleClickOp(slotProps, 'modi')"
            v-if="manager && slotProps.row.status === WORKORDER_STATUS.POSTED">
            <t-icon name="chat"></t-icon>
          </t-button>
          <!-- <a class="t-button-link" @click="rehandleClickOp(slotProps, 'info')">查看</a>
          <a class="t-button-link" @click="rehandleClickOp(slotProps, 'modi')" v-show="manager && row.status === WORKORDER_STATUS.POSTED">回复</a> -->
          <!-- <a class="t-button-link" @click="handleClickDelete(slotProps)">删除</a> -->
        </template>
      </t-table>
      <!-- <t-dialog header="确认删除当前所选合同？" :body="confirmBody" :visible.sync="confirmVisible" @confirm="onConfirmDelete" :onCancel="onCancel"></t-dialog> -->
    </div>
  </div>
</template>

<script>
  import {
    prefix
  } from '@/config/global';
  import Trend from '@/components/trend/index.vue';
  import Card from '@/components/card/index.vue';

  import {
    WORKORDER_STATUS,
    WORKORDER_STATUS_OPTIONS,
    CONTRACT_TYPES,
    CONTRACT_TYPE_OPTIONS,
    CONTRACT_PAYMENT_TYPES
  } from '@/constants';

  export default {
    name: 'list-table',
    components: {
      Trend,
      Card
    },
    data() {
      return {
        modiVisible: false,
        manager: false,
        defaultTrue: true,
        workorderInfo: {},
        infoVisible: false,
        postVisible: false,
        postValue: '',
        WORKORDER_STATUS,
        WORKORDER_STATUS_OPTIONS,
        CONTRACT_TYPES,
        CONTRACT_TYPE_OPTIONS,
        CONTRACT_PAYMENT_TYPES,
        prefix,
        formData: {
          content: '',
          _id: '',
          status: ''
        },
        data: [],
        dataLoading: false,
        value: 'first',
        columns: [{
            title: '工单编号',
            width: 125,
            fixed: 'left',
            ellipsis: true,
            colKey: '_id'
          },
          {
            title: '工单内容',
            // minWidth: '300',
            align: 'left',
            // ellipsis: true,
            colKey: 'info'
            // width: 300
          },
          {
            title: '工单状态',
            colKey: 'status',
            width: 125,
            cell: {
              col: 'status'
            }
          },

          {
            title: '提交时间',
            colKey: 'time',
            width: 150,
            cell: {
              col: 'time'
            }
          },
          // {
          //   title: '合同类型',
          //   width: 200,
          //   ellipsis: true,
          //   colKey: 'contractType'
          // },
          // {
          //   title: '合同收付类型',
          //   width: 200,
          //   ellipsis: true,
          //   colKey: 'paymentType'
          // },
          // {
          //   title: '合同金额 (元)',
          //   width: 200,
          //   ellipsis: true,
          //   colKey: 'amount'
          // },
          {
            align: 'center',
            fixed: 'right',
            width: 100,
            colKey: 'op',
            title: '操作'
          }
        ],
        rowKey: 'index',
        tableLayout: 'auto',
        verticalAlign: 'top',
        bordered: true,
        hover: true,
        rowClassName: rowKey => `${rowKey}-class`,
        // 与pagination对齐
        pagination: {
          defaultPageSize: 10,
          total: 100,
          defaultCurrent: 1,
          pageSizeOptions: [5, 10, 20, 50]
        },
        pages: {
          current: 1,
          pageSize: 10
        },
        confirmVisible: false,
        deleteIdx: -1
      };
    },
    computed: {
      // confirmBody() {
      //   if (this.deleteIdx > -1) {
      //     const { name } = this.data?.[this.deleteIdx];
      //     return `删除后，${name}的所有合同信息将被清空，且无法恢复`;
      //   }
      //   return '';
      // }
    },
    mounted() {
      // console.log(this.$store.state.user.userInfo.type)
      if (localStorage.getItem('ovcf-token') != undefined) {
        console.log('set token');
        this.$store.commit('user/setToken', localStorage.getItem('ovcf-token'));
        this.$store.commit('user/setUserInfo', JSON.parse(localStorage.getItem('info')));
      }
      this.dataLoading = true;
      this.$request
        .post('/doctor-workorder?type=list&pageSize=10&current=1', {
          content: "",
          id: -1,
          status: -1
        })
        .then(res => {
          if (res.code === 0) {
            console.log(res);
            this.pagination.total = res.count;
            this.data = res.info;
          }
        })
        .catch(e => {
          this.$message.error('错误！');
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
      this.manager = this.$store.state.user.userInfo.type == 'Doctor' ? false : true;
      if (this.manager) {
        this.columns[4].width = 150;
      }
    },
    methods: {
      closeInfo() {
        this.infoVisible = false;
        this.postVisible = false;
        this.postValue = '';
        this.modiVisible = false;
        this.workorderInfo = {};
      },
      showPostWorkorder() {
        this.postVisible = true;
      },
      async postWorkorder(type) {
        if (type == 'new') {
          this.$request
            .post('/doctor-workorder?type=post', {
              content: this.postValue
            })
            .then(res => {
              if (res.code === 0) {
                this.$message.success('提交成功！');
                // this.onSubmit();
                // this.closeInfo();
              } else {
                this.$message.error(res.data.info);
              }
            })
            .catch(e => {
              this.$message.error('提交失败！');
              console.log(e);
            })
            .finally(() => {
              this.onSubmit();
              this.closeInfo();
            });
        } else if (type == 'modi') {
          this.workorderInfo.status = this.workorderInfo.tempstatus;
          this.$request
            .post('/doctor-workorder?type=modi', {
              content: this.workorderInfo
            })
            .then(res => {
              if (res.code === 0) {
                this.$message.success('提交成功！');
                // this.onSubmit();
                // this.closeInfo();
              } else {
                this.$message.error(res.data.info);
              }
            })
            .catch(e => {
              this.$message.error('提交失败！');
              console.log(e);
            })
            .finally(() => {
              this.onSubmit();
              this.closeInfo();
            });
        }
      },
      onReset(data) {
        console.log(data);
      },
      async onSubmit(data) {
        // this.pagination.current = 1;
        let tempData = JSON.parse(JSON.stringify(this.formData))
        console.log("before", tempData);
        if (this.formData.status === "") {
          tempData.status = -1
        }
        if (this.formData._id === "") {
          tempData._id = -1
        }
        console.log("after", tempData)
        this.$request
          .post('/doctor-workorder?type=list&pageSize=' + this.pages.pageSize + '&current=' + this.pages.current,
            tempData)
          .then(res => {
            if (res.code === 0) {
              console.log(res);
              this.pagination.total = res.count;
              if (tempData.content == '') {
                this.data = res.info;
                // } else {
                //   let reg = new RegExp('[\\s\\S]*' + this.formData.content + '[\\s\\S]*', 'i');
                //   // console.log(reg)
                //   this.data = res.info.filter(item => {
                //     if (reg.test(item.info)) {
                //       return item;
                //     }
                //   });
              }
            }
          })
          .catch(e => {
            console.log(e);
          })
          .finally(() => {
            this.dataLoading = false;
          });
      },
      async rehandlePageChange(curr, pageInfo) {
        console.log('分页变化', curr, pageInfo);
        this.pages.pageSize = curr.pageSize;
        this.pages.current = curr.current;
        await this.onSubmit();
      },
      rehandleChange(changeParams, triggerAndData) {
        console.log('统一Change', changeParams, triggerAndData);
      },
      rehandleClickOp({
        text,
        row
      }, type) {
        console.log(text, row);
        this.workorderInfo = row;
        if (type == 'info') this.infoVisible = true;
        else if (type == 'modi') this.modiVisible = true;
      },
      handleClickDelete(row) {
        this.deleteIdx = row.rowIndex;
        this.confirmVisible = true;
      }
      // onConfirmDelete() {
      //   // 真实业务请发起请求
      //   this.data.splice(this.deleteIdx, 1);
      //   this.pagination.total = this.data.length;
      //   this.confirmVisible = false;
      //   this.$message.success('删除成功');
      //   this.resetIdx();
      // },
      // onCancel() {
      //   this.resetIdx();
      // },
      // resetIdx() {
      //   this.deleteIdx = -1;
      // }
    }
  };
</script>

<style lang="less">
  @import './workorder.less';

  .list-common-table {
    background-color: @bg-color-container;
    padding: 30px 32px;
    border-radius: @border-radius;

    .table-container {
      margin-top: 30px;
    }
  }

  .form-item-content {
    width: 100%;
  }

  .operation-container {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  .payment-col {
    display: flex;

    .trend-container {
      display: flex;
      align-items: center;
      margin-left: 8px;
    }
  }
</style>
